package com.roadmap.ajax.handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.log4j.Logger;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.roadmap.common.RdcLogger;
import com.roadmap.struts.action.ActionConst;

/** wrap the real object and return a proxy instance of the object */
public class HandlerProxy implements InvocationHandler {
	private final static Logger _log = RdcLogger
			.getLogger(HandlerProxy.class);
	private Object _obj = null;

	private HandlerProxy(Object obj) {
		this._obj = obj;
	}

	/** get an object proxy */
	public static Object newInstance(Object obj) {
		ClassLoader loader = obj.getClass().getClassLoader();
		Class[] funcs = obj.getClass().getInterfaces();
		return Proxy.newProxyInstance(loader, funcs, new HandlerProxy(obj));
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if (isLoggedOn()) {
			return method.invoke(_obj, args);
		}
		/*
		else {
			// if the user don't log on, redirect to the logon page
			
			WebContext webCxt = WebContextFactory.get();
			if (webCxt != null) {
				webCxt.getHttpServletResponse().sendRedirect(
						webCxt.getHttpServletRequest().getContextPath()
								+ ActionConst.LOGON_SERVLET);
			}
			
		}
		*/
		return null;
	}

	private boolean isLoggedOn() {
		WebContext webCxt = WebContextFactory.get();
		if (webCxt != null) {
			Object uid = webCxt.getSession().getAttribute(
					ActionConst.Aspirant_Id_In_Session);
			if (uid != null) {
				return true;
			}
		}
		else {
			_log.error("Can't get the web context factory.");
		}
		return false;
	}

	public static void main(String[] args) {
		// ILogicHandler handler = new LogicHandler();
		// handler = (ILogicHandler) newInstance(handler);
		// handler.save("chen");
	}
}
